<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/5/10
 * Time: 9:47
 */

namespace app\index\model;


use think\Model;

class CrmMediaNext extends Model
{

    public function customer(){
        return $this->hasMany('CrmCustomer','source_type','type');
    }

    public function mediaNextList($input){
        $media = $this->limit($input['rows'])->page($input['page'])->select();
        $total = $this->count();
        return ['list'=>$media,'total'=>$total];
    }

    private function customers($where){
        $res =   $this->withCount(['customer'=>function($query) use ($where) {
            $query->where($where);
        }])->select();
        return $res;
    }

    private function refund($where){
        $where['is_refund']=1;
        $res =   $this->withCount(['customer'=>function($query) use ($where){
            $query->where($where);
        }])->select();
        return $res;
    }

    private function publicPaytype($where){
        $where['public_paytype']=['in',[2,3]];
        $res =   $this->withCount(['customer'=>function($query)use ($where){
            $query->where($where);
        }])->select();
        return $res;
    }

    public function mediaStatistics($query){
        $where=[];
        if(isset($query['endtime']) && isset($query['starttime'])){
            $where['date']=['between',[strtotime($query['starttime']),strtotime($query['endtime'])]];
        }
        $customers = $this->customers($where);
        $refund = $this->refund($where);
        $publicPaytype = $this->publicPaytype($where);
        foreach ($customers as $key=>&$value){
            $value['customer']=$value['customer_count'];
            $value['refund']=$refund[$key]['customer_count'];
            $value['public_paytype']=$publicPaytype[$key]['customer_count'];
        }
        return $customers;
    }

}